package com.yzf.enterprise.common.utils.http;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 通用http发送方法
 */
public final class HttpUtils {

    /**
     * get请求
     */
    public static String sendGet(String url) {
        String result = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * post同步请求
     *
     * @param data 提交的参数为key=value&key1=value1的形式
     */
    public static String sendPost(String url, String data) {
        String result = null;
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            Response response = httpClient.newCall(request).execute();
            if(response!=null){
                result = response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * post异步请求
     *
     * @param data 提交的参数为key=value&key1=value1的形式
     */
    public static String sendPostAsynch(String url, String data) {
        String result = null;
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), data);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            httpClient.newCall(request).enqueue(new Callback(){
                @Override
                public void onFailure(Call call,IOException e){
                    System.out.println("Faile");
                }
                @Override
                public void onResponse(Call call,Response response) throws IOException{
                    System.out.println(response.body().string());
                }
            });
//            result = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private HttpUtils() {
    }

    ///**
    // * 向指定 URL 发送GET方法的请求
    // *
    // * @param url   发送请求的 URL
    // * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
    // * @return 所代表远程资源的响应结果
    // */
    //public static String sendGet(String url, String param) {
    //    StringBuilder result = new StringBuilder();
    //    BufferedReader in = null;
    //    try {
    //        String urlNameString = url + "?" + param;
    //        log.info("sendGet - {}", urlNameString);
    //        URL realUrl = new URL(urlNameString);
    //        URLConnection connection = realUrl.openConnection();
    //        connection.setRequestProperty("accept", "*/*");
    //        connection.setRequestProperty("connection", "Keep-Alive");
    //        connection.setRequestProperty("enterprise-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    //        connection.connect();
    //        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    //        String line;
    //        while ((line = in.readLine()) != null) {
    //            result.append(line);
    //        }
    //        log.info("recv - {}", result);
    //    } catch (ConnectException e) {
    //        log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
    //    } catch (SocketTimeoutException e) {
    //        log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
    //    } catch (IOException e) {
    //        log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
    //    } catch (Exception e) {
    //        log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
    //    } finally {
    //        try {
    //            if (in != null) {
    //                in.close();
    //            }
    //        } catch (Exception ex) {
    //            log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
    //        }
    //    }
    //    return result.toString();
    //}
    //
    ///**
    // * 向指定 URL 发送POST方法的请求
    // *
    // * @param url   发送请求的 URL
    // * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
    // * @return 所代表远程资源的响应结果
    // */
    //public static String sendPost(String url, String param) {
    //    PrintWriter out = null;
    //    BufferedReader in = null;
    //    StringBuilder result = new StringBuilder();
    //    try {
    //        String urlNameString = url + "?" + param;
    //        log.info("sendPost - {}", urlNameString);
    //        URL realUrl = new URL(urlNameString);
    //        URLConnection conn = realUrl.openConnection();
    //        conn.setRequestProperty("accept", "*/*");
    //        conn.setRequestProperty("connection", "Keep-Alive");
    //        conn.setRequestProperty("enterprise-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    //        conn.setRequestProperty("Accept-Charset", "utf-8");
    //        conn.setRequestProperty("contentType", "utf-8");
    //        conn.setDoOutput(true);
    //        conn.setDoInput(true);
    //        out = new PrintWriter(conn.getOutputStream());
    //        out.print(param);
    //        out.flush();
    //        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
    //        String line;
    //        while ((line = in.readLine()) != null) {
    //            result.append(line);
    //        }
    //        log.info("recv - {}", result);
    //    } catch (ConnectException e) {
    //        log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
    //    } catch (SocketTimeoutException e) {
    //        log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
    //    } catch (IOException e) {
    //        log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
    //    } catch (Exception e) {
    //        log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
    //    } finally {
    //        try {
    //            if (out != null) {
    //                out.close();
    //            }
    //            if (in != null) {
    //                in.close();
    //            }
    //        } catch (IOException ex) {
    //            log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
    //        }
    //    }
    //    return result.toString();
    //}

}
